package com.training.micrservices.eureka.controller;

import com.training.micrservices.eureka.openfeign.EurekaClientFeign;
import lombok.SneakyThrows;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;

@RestController
@RequestMapping("/eureka")
public class TestController {

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private EurekaClientFeign eurekaClientFeign;

    @RequestMapping("/hello")
    public String hello() {
        System.out.println(discoveryClient.getServices());
        ServiceInstance choose = loadBalancerClient.choose("micrservice-eureka-client");
        System.out.println(choose.getPort());
        String forObject = restTemplate.getForObject("http://micrservice-eureka-client/eureka/hello", String.class);
        System.out.println(forObject);
        String hello = eurekaClientFeign.hello();
        System.out.println(hello);
        return "hello";
    }

    /**
     * 多文件上传
     */
    @PostMapping("/upload")
    @SneakyThrows
    public Object upload(MultipartHttpServletRequest request) {
        Iterator<String> iterator = request.getFileNames();
        ArrayList<String> list = new ArrayList<>();
        while (iterator.hasNext()) {
            String filedName = iterator.next();
            String fileName = eurekaClientFeign.upload(request.getFile(filedName));
            System.out.println(fileName);
            list.add(fileName);
        }
        return list;
    }
}